<script setup>
import PageHeader from "@/components/PageHeader/index.vue";
import {nextTick, onMounted, ref} from "vue";
import {convertISOToBasicString} from "@/utils/common1.js";
import {changeAbsApply, deleteAbsApply, listStudentAbsence, postAbsApply, postAbsBack} from "@/api/absence/index.js";
import StepHeader from "@/components/StepHeader/index.vue";
import {ElMessage} from "element-plus";
import {absStatusFormat, urlToFile} from "@/utils/common_absence.js";
import Pagination from "@/components/Pagination/index.vue";

//查询条件
const queryParams = ref({
  current: 1,
  size: 20,
  data: {}
})

//查询条件控制
const queryParamsControl = ref({
  table: {
    total: 0,
    loading: false,
    data: []
  },
  status: {
    option: [],
    loading: false
  }
})

const tableRef = ref() //表格ref
const multipleSelection = ref([]); // 已选择的row

const selectable = (row) => ![1, 2].includes(row.id);

const handleSelectionChange = (val) => {
  multipleSelection.value = val;
  console.log("val", val);
};

const getList = async () => {
  const data = await listStudentAbsence(queryParams.value)
  // console.log(data)

  queryParamsControl.value.table.data = data.data
  queryParamsControl.value.table.total = data.count
  queryParamsControl.value.table.loading = false
}

let formRef = ref(null)
let applyForm = ref({ //申请form
  leavingTime: '',
  backingTime: '',
  reason: '',
  position: '',
  number: '',
  picture: '',
})

let applyForm_rules = ref({
  leavingTime: [
    {
      required: true,
      message: "请选择离校时间",
      trigger: "blur",
    },
  ],
  reason: [
    {
      required: true,
      message: "请输入离校原因",
      trigger: "blur",
    },
  ],
  position: [
    {
      required: true,
      message: "请输入离校期间所在地",
      trigger: "blur",
    },
  ],
  number: [
    {
      required: true,
      message: "请输入家长联系方式",
      trigger: "blur",
    },
  ],
  picture: [
    {
      required: true,
      message: "请上传图片",
      trigger: "blur",
    },
  ],
})

let dia_applyForm = ref(false) // 请假form
let dialogVisible_check = ref(false) // check弹窗
let DateRange = ref([]) // 请假时间范围

const handleClose_applyForm = async () => {
  handleReset_apply() //清除form内容
  rowCache.value = null //清除当前行缓存
  dia_applyForm.value = false;
  await nextTick(() => {
    formRef.value.clearValidate()
  });
};

let rowCache = ref(null) //编辑当前行，缓存row
const handleOpen_applyForm = async (row) => {
  console.log(applyForm.value.picture)
  if (row) {// 编辑模式
    rowCache.value = row
    const file = await urlToFile(row.url)
    //表单
    applyForm.value = {
      leavingTime: row.leavingTime,
      backingTime: row.backingTime,
      reason: row.reason,
      position: row.position,
      number: row.number,
      picture: file,
    }
    DateRange.value.push(row.leavingTime, row.backingTime) //时间范围缓存（显示值

    imgUrl.value = row.url //图片显示url

    dia_applyForm.value = true;
  } else {
    dia_applyForm.value = true;
  }
};

const handleDateRange = (value) => {
  applyForm.value.leavingTime = convertISOToBasicString(value[0])
  applyForm.value.backingTime = convertISOToBasicString(value[1])
}

// 重置applyForm
const handleReset_apply = () => {
  console.log("重置")
  applyForm.value = {
    leavingTime: '',
    backingTime: '',
    reason: '',
    position: '',
    number: '',
    picture: '',
  }
  DateRange.value = [] //日期范围缓存
  imgUrl.value = null //图片url缓存
  urlList.value = [] //图片回显list
}

const handleAbsenceApply = () => {
  if(rowCache.value === null){// 初次提交
    postAbsenceApply()

  } else {// 编辑
    changeAbsenceApply()
  }
}

// 提交申请
const postAbsenceApply = async () => {
  const res = await postAbsApply(applyForm.value)
  if(!res.code) {
    dialogVisible_check.value = false
    dia_applyForm.value = false
    ElMessage.success('提交成功')
    handleReset_apply()
    await getList()
  } else {
    ElMessage.error('请重新提交')
  }
}

// 编辑
const changeAbsenceApply = async () => {
  const applicationId = rowCache.value.id
  const res = await changeAbsApply(applyForm.value,applicationId)
  if(!res.code) {
    dialogVisible_check.value = false
    dia_applyForm.value = false
    ElMessage.success('修改成功')
    handleReset_apply()
    await getList()
  } else {
    ElMessage.error('请重新提交')
  }
}

onMounted(() => {
  getList()
})

let imgDrawer = ref(false) //抽屉开关
let imgUrl = ref() //回显url
let urlList = ref([]) //预览图片用

//打开抽屉img
const handleOpenImgDraw = (row) => {
  urlList.value = [] //先清空原先的
  rowCache.value = row
  urlList.value.push(row.url)
  imgDrawer.value = true
}

const uploadImg = async (item) => {
  urlList.value = [] //先置空
  applyForm.value.picture = item.raw //图片文件本体
  imgUrl.value = URL.createObjectURL(item.raw) //回显用
  console.log("图片url：", imgUrl)
  urlList.value.push(imgUrl.value)
}

const imgFormat = (rawFile) => {
  console.log("111")
  if (rawFile.type !== 'image/jpeg'&& rawFile.type !== 'image/png') {
    ElMessage.error('请上传图片格式!')
    return false
  }
  return true
}


const dia_preview_img = ref(false)
const handleImgPreview = () => {
  dia_preview_img.value = true
}

const checkBack = async (row) => {
  const res = await postAbsBack(row.id)
  if(!res.code){
    ElMessage.success("已申请销假")
    await getList()
  }else{
    ElMessage.error('请重试')
  }
}

const deleteApply = async (applicationId) => {
  const res = await deleteAbsApply(applicationId)
  if(!res.code){
    ElMessage.success("已撤回")
    await getList()
  }else{
    ElMessage.error('请重试')
  }
}

</script>

<template>
<div class="app-container">
  <el-card class="box">
    <PageHeader>
      <template #left>
        <ElButton class="exportBtn" type="success" @click="handleOpen_applyForm(null)">
          <el-icon><Plus /></el-icon>申请离校
        </ElButton>
      </template>
      <template #right>
        <ElButton class="queryBtn" plain @click="getList">刷新列表</ElButton>
      </template>
    </PageHeader>
  </el-card>
  <el-card class="box">
    <el-table
        height="400"
        ref="tableRef"
        v-loading="queryParamsControl.table.loading"
        :data="queryParamsControl.table.data"
        row-key="id"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="expand">
        <template #default="props">
          <div class="table_description">
            <el-descriptions :column="2" class="cell_description" border>
              <el-descriptions-item label="联系方式">{{props.row.number}}</el-descriptions-item>
              <el-descriptions-item label="请假证明">
                <el-button type="primary" link @click="handleOpenImgDraw(props.row)">查看图片
                </el-button>
              </el-descriptions-item>
              <el-descriptions-item label="离校时间">{{props.row.leavingTime}}</el-descriptions-item>
              <el-descriptions-item label="离校期间所在地">{{props.row.position}}</el-descriptions-item>
              <el-descriptions-item label="预计返校时间">{{props.row.backingTime}}</el-descriptions-item>
              <el-descriptions-item v-if="[1,2,3,4,5].includes(props.row.status)" label="批假时间">{{props.row.approvalTime}}</el-descriptions-item>
              <el-descriptions-item v-if="[3,4,5].includes(props.row.status)" label="申请销假时间">{{props.row.checkingTime}}</el-descriptions-item>
              <el-descriptions-item v-if="[4,5].includes(props.row.status)" label="销假时间">{{props.row.approvedTime}}</el-descriptions-item>
            </el-descriptions>
          </div>
        </template>
      </el-table-column>
      <el-table-column type="selection" :selectable="selectable" fixed="left" width="50" />
      <el-table-column type="index" fixed="left" width="54" label="序号" />
      <el-table-column label="请假状态" prop="status" width="200" :formatter="absStatusFormat()" show-overflow-tooltip />
      <el-table-column label="请假原因" prop="reason" show-overflow-tooltip />
      <el-table-column label="申请时间" prop="applicationTime" show-overflow-tooltip />
      <ElTableColumn label="操作" width="124" fixed="right">
        <template #default="{row}">
          <el-button
              v-if="[0].includes(row.status)"
              plain
              type="success"
              @click="handleOpen_applyForm(row)"
              link
          >编辑</el-button>
          <el-popconfirm title="确定撤回?"
                         @confirm="deleteApply(row.id)">
            <template #reference>
              <el-button
                  v-if="[0].includes(row.status)"
                  plain
                  type="danger"
                  link
              >撤回</el-button>
            </template>
          </el-popconfirm>
          <el-button
              v-if="[2].includes(row.status)"
              plain
              type="warning"
              @click="checkBack(row)"
              link
          >销假</el-button>
        </template>
      </ElTableColumn>
    </el-table>
    <el-pagination
        @size-change="getList"
        @current-change="getList"
        v-model:current-page="queryParams.current"
        v-model:page-size="queryParams.size"
        :page-sizes="[5, 10, 20, 50]"
        :background="true"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="queryParamsControl.table.total"
        style="margin-top: 8px"
    />
  </el-card>

  <el-dialog v-model="dia_applyForm"
             width="650"
             :before-close="handleClose_applyForm">
    <div style="height: 52vh">
      <el-scrollbar max-height="360" wrap-style="overflow-x: hidden">
        <div style="width: 100%">
          <el-form ref="formRef" :model="applyForm" :rules="applyForm_rules" inline>
            <StepHeader title="请假信息" />
            <el-row>
              <el-col :span="24">
                <el-form-item label="离校时间" prop="DateRange">
                  <el-date-picker
                      v-model="DateRange"
                      type="datetimerange"
                      range-separator="To"
                      start-placeholder="起始日期"
                      end-placeholder="结束日期"
                      @change="handleDateRange"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="离校原因" prop="reason">
                  <el-input style="width: 350px" v-model="applyForm.reason"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="离校期间所在地" prop="position">
                  <el-input style="width: 365px" v-model="applyForm.position"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="10">
                <el-form-item label="监护人电话" prop="number">
                  <el-input v-model="applyForm.number"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="10">
                <el-form-item label="图片证明">
                  <el-upload
                        class="avatar-uploader"
                        action="#"
                        :auto-upload="false"
                        :multiple="false"
                        :show-file-list="false"
                        :on-change="uploadImg"
                        :before-upload="imgFormat"
                    >
                      <el-icon v-if="applyForm.picture == ''" class="avatar-uploader-icon"><Plus /></el-icon>
                      <el-image class="img_file" :fit="'fill'" :src="imgUrl" v-else />
                    </el-upload>
                </el-form-item>
              </el-col>
              <el-col :span="10" v-if="applyForm.picture">
                <el-button type="primary" link @click="handleImgPreview()">查看</el-button>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-scrollbar>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleReset_apply">重置</el-button>
        <el-button type="success" @click="dialogVisible_check=true">
          提交
        </el-button>
      </div>
    </template>
    <el-dialog
        v-model="dialogVisible_check"
        width="400"
        append-to-body
    >
      <span>确定提交吗？</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible_check=false">取消</el-button>
          <el-button type="success" @click="handleAbsenceApply">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </el-dialog>

  <el-drawer
      v-model="imgDrawer"
      title="图片证明"
      direction="ltr"
  >
    <div class="imgBox">
      <el-image :src="rowCache.url"
                :fit="'fill'"
                :preview-src-list="urlList"
      ></el-image>
    </div>

  </el-drawer>

  <el-dialog v-model="dia_preview_img">
    <el-image :src="imgUrl"
              :fit="'fill'"
              :preview-src-list="urlList"/>
  </el-dialog>

</div>
</template>

<style scoped lang="scss">
.box {
  margin-bottom: 8px;
}

.avatar-uploader .img_file {
  width: 180px;
  height: 120px;
  display: block;
}

.table_description {
  padding-left: 150px;
}

</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 180px;
  height: 120px;
  text-align: center;
}
</style>
